var fs = require('fs')
var userPath = require('../config/pathConfig.js').userPath
var util = require('../utility/util.js')

var Active = require('./activeHandler')

var fileName = 'suggests.data'

var safePathCheck = util.safePathCheck

module.exports = {

    insert: function(body, callback) {
        var handler = body.handler
        var content = body.content
        var suggest = util.createSuggestDb(handler, content)
        safePathCheck(userPath, fileName, function(exists) {
            if (exists) {
                var data = fs.readFileSync(userPath + fileName)
                data = JSON.parse(data)
            } else {
                var data = []
            }
            data.push(suggest)
            data = JSON.stringify(data, null, 4)
            fs.writeFile(userPath + fileName, data, function(err) {
                if (err) {
                    console.log('suggestHandler insert fail. err = ' + err)
                    callback('保存失败')
                } else {
                    var activeType3 = util.createActiveType3(handler, content)
                    Active.insert(activeType3)
                    callback(null, suggest)
                }
            })
        })
    }
}